package com.atdel.demo09;

import java.util.concurrent.*;

/**
 * @BelongsProject: java_study
 * @BelongsPackage: com.atdel.demo09
 * @Author: Del
 * @CreateTime: 2025-03-10  19:02
 * @Description:
 * 案例：
 * 三、定义一个线程类，实现计算m-n的和。创建多个线程，分段计算1-N的和。
 * 如：我们要计算1-1000和的，创建以下三个线程，分别计算
 * 1-100
 * 101-900
 * 901-1000
 * 最后把三个线程的和加起来，就是最终的结果
 * @Version: 1.0
 */
public class ThreadTest {
    public static void main(String[] args) {
        // 使用线程池来管理线程
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        // 创建任务
        MyThread myThread01 = new MyThread(1, 100);
        MyThread myThread02 = new MyThread(101, 900);
        MyThread myThread03 = new MyThread(901, 1000);

        // 提交任务并获取Future
        Future<Integer> future01 = executorService.submit(myThread01);
        Future<Integer> future02 = executorService.submit(myThread02);
        Future<Integer> future03 = executorService.submit(myThread03);

        // 计算最终结果
        try {
            int result = future01.get() + future02.get() + future03.get();
            System.out.println("最终的结果为：" + result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭线程池
            executorService.shutdown();
        }
    }
}

class MyThread implements Callable<Integer> {
    private final int start;
    private final int end;

    public MyThread(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    public Integer call() throws Exception {
        if (start > end) {
            return 0;
        }
        int sum = 0;
        for (int i = start; i <= end; i++) {
            sum += i;
        }
        return sum;
    }
}